package com.nbb.demo.memcached.controller;

import com.nbb.demo.memcached.entity.User;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeoutException;

/**
 * @description:
 * @author: Jerry
 * @time: 2021/3/30 12:05
 */
@RestController
@RequestMapping("/memcached")
public class MemcachedController {

    @Autowired
    private MemcachedClient memcachedClient;

    @RequestMapping("/add")
    public String add(String k, String v) {
        boolean b = false;
        try {
            b = memcachedClient.set(k, 10, v);
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (MemcachedException e) {
            e.printStackTrace();
        }
        return "" + b;
    }

    @RequestMapping("/addUser")
    public String addUser(String k, String v) {
        boolean b = false;
        try {
            b = memcachedClient.set(k, 10, User.builder().username(v).build());
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (MemcachedException e) {
            e.printStackTrace();
        }
        return "" + b;
    }

    @RequestMapping("/get")
    public String get(String k) {
        try {
            Object o = memcachedClient.get(k);
            if (o instanceof User) {
                System.out.println("####user");
            }
            return o.toString();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (MemcachedException e) {
            e.printStackTrace();
        }
        return null;
    }
}
